package com.ysd.lis.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.TDeptGroupMapper;
import com.ysd.lis.mapper.TEmployeeMapper;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.OrganizationPageParam;
import com.ysd.lis.service.*;
import com.ysd.lis.vo.OrgDeptVo;
import com.ysd.lis.vo.OrgLabUserVo;
import com.ysd.util.RedisUserManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_organization 服务实现类
 * </p>
 *
 * @author Peng
 * @since 2021-10-08
 */
@Service
public class SysOrganizationServiceImpl extends ServiceImpl<SysOrganizationMapper, SysOrganization> implements SysOrganizationService {
    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;
    @Autowired
    TDeptGroupMapper tDeptGroupMapper;
    @Autowired
    SysUserDeptMapper sysUserDeptMapper;
    @Autowired
    TEmployeeMapper tEmployeeMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysModuleService sysModuleService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysBasDictService sysBasDictService;
    @Autowired
    SysInterfaceService sysInterfaceService;

    @Autowired
    SysRuleSetService sysRuleSetService;

    @Override
    public Result findOrgAllList() {
        List<Map<String, Object>> list = sysOrganizationMapper.findOrgAllList();
        Map<String, Object> map = new HashMap<>();
        map.put("orgList", list);
        return Result.succ(1, "获取数据成功", map);
    }

    @Override
    public Result findOrgDeptTreeByOrgId(String orgId) {
        //根据组织机构ID查出该组织机构及以下所有子机构和部门
        List<OrgDeptVo> orgDeptList = sysOrganizationMapper.getOrgDeptTreeByOrgId(orgId);
        List<String> ids = orgDeptList.stream().map(OrgDeptVo::getId).collect(Collectors.toList());

        Map returnMap = new HashMap();
        //机构及部门
        List<Map> orgDeptTree = new ArrayList<>();
        for (OrgDeptVo vo : orgDeptList) {
            if (orgId.equals(vo.getId())) {
                Map map = new HashMap();
                map.put("id", vo.getId());
                map.put("name", vo.getName());
                map.put("code", vo.getCode());
                map.put("parentId", vo.getParentId());
                map.put("orgDeptType", vo.getOrgDeptType());
                orgDeptTree.add(map);
            }
        }
        for (Map m : orgDeptTree) {
            List<Map> child = getChildByOrgId(m, orgDeptList, ids);
            m.put("children", child);
        }
        returnMap.put("orgDeptList", orgDeptTree);

        //只获取机构树
        List<OrgDeptVo> orgList = new ArrayList<>();
        List<Map> orgTree = new ArrayList<>();

        for (OrgDeptVo vo : orgDeptList) {
            if (orgId.equals(vo.getId())) {
                Map map = new HashMap();
                map.put("id", vo.getId());
                map.put("name", vo.getName());
                map.put("code", vo.getCode());
                map.put("parentId", vo.getParentId());
                map.put("orgDeptType", vo.getOrgDeptType());
                orgTree.add(map);
            }
            //将所有的机构放到机构集合中
            if ("1".equals(vo.getOrgDeptType())) {
                orgList.add(vo);
            }
        }
        for (Map m : orgTree) {
            List<Map> child = getChildByOrgId(m, orgList, null);
            m.put("children", child);
        }

        returnMap.put("orgList", orgTree);


        return Result.succ(1, "获取数据成功", returnMap);
    }

    private List<Map> getChildByOrgId(Map m, List<OrgDeptVo> orgDeptList, List<String> ids) {
        List<Map> result = new ArrayList();
        if (null != orgDeptList) {
            for (OrgDeptVo vo : orgDeptList) {
                if (StringUtils.isNotBlank(vo.getParentId()) && (vo.getParentId()).equals(m.get("id"))) {
                    Map map = new HashMap();
                    map.put("id", vo.getId());
                    map.put("name", vo.getName());
                    map.put("code", vo.getCode());
                    map.put("parentId", vo.getParentId());
                    map.put("orgDeptType", vo.getOrgDeptType());
                    if (vo.getOrgDeptType().equals("2")) {
                        map.put("orgId", vo.getOrgId());
                        int indexOf = ids.indexOf(vo.getOrgId());
                        if (indexOf >= 0) {
                            map.put("orgName", orgDeptList.get(indexOf).getName());
                        }
                    }
                    result.add(map);
                }
            }
        }
        for (Map ma : result) {
            ma.put("children", getChildByOrgId(ma, orgDeptList, ids));
        }
        if (result.size() == 0) {
            return null;
        }
        return result;
    }

    @Override
    public Result findOrgTree() {
        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        //所有的机构
        List<SysOrganization> organizationList = sysOrganizationMapper.selectList(lambdaQueryWrapper);
        List<String> orgIds = organizationList.stream().map(SysOrganization::getId).collect(Collectors.toList());
        //所有的部门
//        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper1.eq(SysOrgDepartment::getDelFlag, 0);
//        List<SysOrgDepartment> departmentList = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper1);

//        for (SysOrgDepartment dept : departmentList) {
//            String orgId = dept.getOrgId();
//            if (orgIds.indexOf(orgId) >= 0) {
//                dept.setOrgName(organizationList.get(orgIds.indexOf(orgId)).getName());
//            }
//        }

        //获取机构及部门树
//        List<Map> parentTree = new ArrayList<>();
//        for (SysOrganization o : organizationList) {
//            if (StringUtils.isBlank(o.getParentId())) {
//                Map map = new HashMap();
//                map.put("id", o.getId());
//                map.put("name", o.getName());
//                map.put("code", o.getCode());
//                map.put("type", o.getType());
//                map.put("address", o.getAddress());
//                map.put("contactName", o.getContactName());
//                map.put("contactTel", o.getContactTel());
//                map.put("area", o.getArea());
//                map.put("areaCode", o.getAreaCode());
//                map.put("faxNum", o.getFaxNum());
//                map.put("postal", o.getPostal());
//                map.put("province", o.getProvince());
//                map.put("provinceCode", o.getProvinceCode());
//                map.put("city", o.getCity());
//                map.put("cityCode", o.getCityCode());
//                map.put("parentId", o.getParentId());
//                map.put("parentName", null);
//                map.put("orgDeptType", "1");
//                parentTree.add(map);
//            }
//        }
//        for (Map m : parentTree) {
//            List<Map> child = getChild(m, organizationList, departmentList);
//            m.put("children", child);
//        }

        Map<String, Object> resultMap = new HashMap<>();
        //resultMap.put("orgDeptTree", parentTree);


        //只获取机构树
        List<Map> orgTree = new ArrayList<>();
        for (SysOrganization o : organizationList) {
            if (StringUtils.isBlank(o.getParentId())) {
                Map map = new HashMap();
                map.put("id", o.getId());
                map.put("name", o.getName());
                map.put("code", o.getCode());
                map.put("type", o.getType());
                map.put("address", o.getAddress());
                map.put("contactName", o.getContactName());
                map.put("contactTel", o.getContactTel());
                map.put("area", o.getArea());
                map.put("areaCode", o.getAreaCode());
                map.put("faxNum", o.getFaxNum());
                map.put("postal", o.getPostal());
                map.put("province", o.getProvince());
                map.put("provinceCode", o.getProvinceCode());
                map.put("city", o.getCity());
                map.put("cityCode", o.getCityCode());
                map.put("parentId", o.getParentId());
                map.put("parentName", null);
                map.put("orgDeptType", "1");
                orgTree.add(map);
            }
        }

        for (Map m : orgTree) {
            List<Map> child = getChild(m, organizationList, null);
            m.put("children", child);
        }
        resultMap.put("orgTree", orgTree);
        return Result.succ(1, "查询成功", resultMap);
    }


    @Override
    public Result findOrgTreePaltform() {
        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        //所有的机构
        List<SysOrganization> organizationList = sysOrganizationMapper.selectList(lambdaQueryWrapper);
        List<String> orgIds = organizationList.stream().map(SysOrganization::getId).collect(Collectors.toList());
        //所有的部门
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> departmentList = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper1);

        for (SysOrgDepartment dept : departmentList) {
            String orgId = dept.getOrgId();
            if (orgIds.indexOf(orgId) >= 0) {
                dept.setOrgName(organizationList.get(orgIds.indexOf(orgId)).getName());
            }
        }
        //获取机构及部门树
        List<Map> parentTree = new ArrayList<>();
        for (SysOrganization o : organizationList) {
            if (StringUtils.isBlank(o.getParentId())) {
                Map map = new HashMap();
                map.put("id", o.getId());
                map.put("name", o.getName());
                map.put("code", o.getCode());
                parentTree.add(map);
            }
        }
        for (Map m : parentTree) {
            List<Map> child = getChild(m, organizationList, departmentList);
            m.put("deptList", child);
        }
        return Result.succ(1, "查询成功", parentTree);
    }


    private List<Map> getChild(Map m, List<SysOrganization> organizationList, List<SysOrgDepartment> departmentList) {
        List<Map> result = new ArrayList();
        if (null != departmentList) {
            for (SysOrgDepartment dt : departmentList) {
                if (StringUtils.isBlank(dt.getParentId()) && dt.getOrgId().equals(m.get("id"))) {
                    Map map = new HashMap();
                    map.put("id", dt.getId());
                    map.put("name", dt.getName());
                    map.put("code", dt.getCode());
                    map.put("orgId", dt.getOrgId());
                    map.put("orgName", dt.getOrgName());
                    map.put("isCheck", dt.getIsCheck());
                    map.put("isSample", dt.getIsSample());
                    map.put("parentId", m.get("id"));
                    map.put("parentName", m.get("name"));
                    map.put("orgDeptType", "2");
                    result.add(map);
                } else if (StringUtils.isNotBlank(dt.getParentId()) && dt.getParentId().equals(m.get("id"))) {
                    Map map = new HashMap();
                    map.put("id", dt.getId());
                    map.put("name", dt.getName());
                    map.put("code", dt.getCode());
                    map.put("orgId", dt.getOrgId());
                    map.put("orgName", dt.getOrgName());
                    map.put("isCheck", dt.getIsCheck());
                    map.put("isSample", dt.getIsSample());
                    map.put("parentId", dt.getParentId());
                    map.put("parentName", m.get("name"));
                    map.put("orgDeptType", "2");
                    result.add(map);
                }
            }
        }

        for (SysOrganization to : organizationList) {
            if (StringUtils.isNotBlank(to.getParentId()) && to.getParentId().equals(m.get("id"))) {
                Map map = new HashMap();
                map.put("id", to.getId());
                map.put("name", to.getName());
                map.put("code", to.getCode());
                map.put("type", to.getType());
                map.put("address", to.getAddress());
                map.put("contactName", to.getContactName());
                map.put("contactTel", to.getContactTel());
                map.put("area", to.getArea());
                map.put("areaCode", to.getAreaCode());
                map.put("faxNum", to.getFaxNum());
                map.put("postal", to.getPostal());
                map.put("province", to.getProvince());
                map.put("provinceCode", to.getProvinceCode());
                map.put("city", to.getCity());
                map.put("cityCode", to.getCityCode());
                map.put("parentId", to.getParentId());
                map.put("parentName", m.get("name"));
                map.put("orgDeptType", "1");
                result.add(map);
            }
        }

        for (Map ma : result) {
            ma.put("children", getChild(ma, organizationList, departmentList));
        }
        if (result.size() == 0) {
            return null;
        }
        return result;
    }

    @Override
    public Result findOrganizationPageList(OrganizationPageParam company) {
        Page<SysOrganization> page = new Page<>();
        page.setCurrent(company.getPageIndex());
        page.setSize(company.getPageSize());

        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        if (company.getType() != null && company.getType().size() > 0) {
            lambdaQueryWrapper.in(SysOrganization::getType, company.getType());
        }
        if (StringUtils.isNotBlank(company.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysOrganization::getName, company.getKeywords()).or().like(SysOrganization::getCode, company.getKeywords()));
        }
        Page<SysOrganization> tOrganizationPage = sysOrganizationMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", tOrganizationPage);
    }

    @Override
    public Result findOrganizationList(OrganizationPageParam company) {
        SysUser sysUser = RedisUserManager.getUser();

        MPJLambdaWrapper<SysRole> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysRole.class).leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getId);
        queryWrapper.eq(SysRole::getDelFlag, 0);
        queryWrapper.eq(SysUserRole::getDelFlag, 0);
        queryWrapper.eq(SysUserRole::getUserId, sysUser.getId());
        List<SysRole> sysRoles = sysRoleMapper.selectList(queryWrapper);
        List<String> roleNames = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());

        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        if (StringUtils.isNotBlank(sysUser.getOrgId()) && !roleNames.contains("管理员")) {
            lambdaQueryWrapper.eq(SysOrganization::getId, sysUser.getOrgId());
        }
        if (StringUtils.isNotBlank(company.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysOrganization::getName, company.getKeywords()).or().like(SysOrganization::getCode, company.getKeywords()));
        }

        List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", sysOrganizations);
    }


    @Override
    public Result addOrg(SysOrganization sysOrganization) {
        int i = this.baseMapper.insert(sysOrganization);
        Map<String, Object> resultMap = new HashMap<>();
        if (i == 1) {
            resultMap.put("orgId", sysOrganization.getId());
            return Result.succ(1, "添加组织机构成功", resultMap);
        } else {
            return Result.fail("添加失败");
        }
    }

    @Override
    public Result findOrgById(String id) {
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(id);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("org", sysOrganization);
        return Result.succ(1, "获取数据成功", resultMap);
    }

    @Override
    public Result findOrgChildList(String orgId) {
        List<Map<String, Object>> list = sysOrganizationMapper.findOrgChildList(orgId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orgList", list);
        return Result.succ(1, "获取数据成功", resultMap);
    }

    @Override
    public Result findOrgNoParentList(String orgId, Integer type) {
        List<Map<String, Object>> list = sysOrganizationMapper.findOrgNoParentList(orgId, type);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orgList", list);
        return Result.succ(1, "获取数据成功", resultMap);
    }

    @Override
    public Result setOrgParentIdList(List<Map> list) {
        for (Map m : list) {
            SysOrganization sysOrganization = new SysOrganization();
            sysOrganization.setId(String.valueOf(m.get("id")));
            sysOrganization.setParentId(String.valueOf(m.get("parentId")));
            this.getBaseMapper().updateById(sysOrganization);
        }
        return Result.succ(1, "获取数据成功", null);
    }

    @Override
    public Result editOrg(SysOrganization sysOrganization) {
        int i = sysOrganizationMapper.updateById(sysOrganization);
        Map<String, Object> resultMap = new HashMap<>();
        if (i == 1) {
            resultMap.put("orgId", sysOrganization.getId());
            return Result.succ(1, "修改组织机构成功", resultMap);
        } else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Result deleteOrg(SysOrganization sysOrganization) {
        int i = sysOrganizationMapper.updateById(sysOrganization);
        Map<String, Object> resultMap = new HashMap<>();
        if (i == 1) {
            resultMap.put("orgId", sysOrganization.getId());
            return Result.succ(1, "删除组织机构成功", resultMap);
        } else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Result deleteOrgOrDept(OrganizationPageParam companyPage) {
        String orgDeptType = companyPage.getOrgDeptType();
        String id = companyPage.getId();
        if (orgDeptType.equals("1")) {
            //删除机构
            //先查询此机构是否有子机构
            LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysOrganization::getParentId, id).eq(SysOrganization::getDelFlag, 0);
            Integer oCnt = sysOrganizationMapper.selectCount(lambdaQueryWrapper);
            if (oCnt == 0) {
                //查看此机构下是否有部门
                LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(SysOrgDepartment::getOrgId, id).eq(SysOrgDepartment::getDelFlag, 0);
                Integer dcnt = sysOrgDepartmentMapper.selectCount(lambdaQueryWrapper1);
                if (dcnt == 0) {
                    //查看此机构下是否有用户
                    LambdaQueryWrapper<SysUser> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper2.eq(SysUser::getOrgId, id).eq(SysUser::getDelFlag, '0');
                    Integer uCnt = sysUserMapper.selectCount(lambdaQueryWrapper2);
                    if (uCnt > 0) {
                        return Result.fail("该机构下存在用户信息，不能删除");
                    } else {
                        SysOrganization sysOrganization = new SysOrganization();
                        sysOrganization.setId(id);
                        sysOrganization.setDelFlag(1);
                        int deleteById = sysOrganizationMapper.updateById(sysOrganization);
                        if (deleteById > 0) {
                            return Result.succ(1, "删除成功", null);
                        } else {
                            return Result.fail("删除失败");
                        }
                    }
                } else {
                    return Result.fail("该机构下存在部门信息，不能删除");
                }
            } else {
                return Result.fail("该机构下存在机构信息，不能删除");
            }


        } else if (orgDeptType.equals("2")) {
            //删除部门
            //先查询此部门下是否有子部门
            LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysOrgDepartment::getParentId, id).eq(SysOrgDepartment::getDelFlag, 0);
            List<SysOrgDepartment> departmentList = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);
            if (departmentList.size() == 0) {
                //查询此部门下是否有部门分组数据
                LambdaQueryWrapper<TDeptGroup> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(TDeptGroup::getDeptId, id).eq(TDeptGroup::getDelFlag, '0');
                Integer selectCount = tDeptGroupMapper.selectCount(lambdaQueryWrapper1);
                if (selectCount > 0) {
                    return Result.fail("该部门下存在分组信息，不能删除");
                } else {
                    //查看此部门下是否存在用户信息
                    LambdaQueryWrapper<SysUserDept> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper2.eq(SysUserDept::getDeptId, id).eq(SysUserDept::getDelFlag, '0');
                    Integer selectCount1 = sysUserDeptMapper.selectCount(lambdaQueryWrapper2);
                    if (selectCount1 > 0) {
                        return Result.fail("该部门下存在用户信息，不能删除");
                    } else {
                        //查看此部门下是否存在人员信息
                        int deleteById = sysOrgDepartmentMapper.deleteById(id);
                        if (deleteById > 0) {
                            return Result.succ(1, "删除成功", null);
                        } else {
                            return Result.fail("删除失败");
                        }
                    }
                }
            } else {
                return Result.fail("该部门下存在部门信息，不能删除");
            }
        } else {
            return Result.fail("无删除信息，请确认");
        }
    }

    @Override
    public Result addLabUser(OrgLabUserVo orgLabUserVo) {
        //先删除后插入
        if (StringUtils.isNotBlank(orgLabUserVo.getId())) {
            sysUserMapper.deleteById(orgLabUserVo.getId());
            LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysUserRole::getUserId, orgLabUserVo.getId());
            sysUserRoleMapper.delete(lambdaQueryWrapper);
        }
        SysUser tuser = new SysUser();
        BeanUtils.copyProperties(orgLabUserVo, tuser);
        tuser.setPassword(SecureUtil.md5(orgLabUserVo.getPassword()));
        tuser.setInitializer("1");
        tuser.setInitializeFlag("0");
        int insert = sysUserMapper.insert(tuser);
        if (insert > 0) {
            if (CollectionUtils.isNotEmpty(orgLabUserVo.getRoles())) {
                orgLabUserVo.getRoles().forEach(a -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(tuser.getId());
                    sysUserRole.setRoleId(a);
                    sysUserRoleMapper.insert(sysUserRole);
                });
                return Result.succ(1, "新增成功", tuser.getId());
            }
        }
        return Result.fail("新增失败");
    }

}
